package com.lee.blepwm.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.lee.blepwm.R;
import com.lee.blepwm.adapter.BleAdapter;
import com.lee.blepwm.model.BleModel;

import java.util.ArrayList;
import java.util.List;

public class BlueToothActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity:";

    private RecyclerView recyclerView;
    private List<BleModel> mData;
    private BleAdapter bleAdapter;

    private Context mContext;

    private BluetoothAdapter blueAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;
        recyclerView = findViewById(R.id.recycler_view);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) recyclerView.getLayoutParams();
        layoutParams.width = ScreenUtils.getScreenWidth() * 3 / 5;
        layoutParams.height = ScreenUtils.getScreenHeight() / 2;
        recyclerView.setLayoutParams(layoutParams);

        mData = new ArrayList<>();
        bleAdapter = new BleAdapter(mContext, mData);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(bleAdapter);

        blueAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueAdapter == null) {
            Toast.makeText(this, "不支持", Toast.LENGTH_SHORT).show();
            return;
        }

        IntentFilter intentFilter = new IntentFilter();//注册广播接收信号
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//开启/关闭蓝牙
//                intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//发现蓝牙广播
        registerReceiver(bluetoothReceiver, intentFilter);//用BroadcastReceiver 来取得结果

        //判断本机蓝牙是否打开
        if (!blueAdapter.isEnabled()) {//如果没打开，则打开蓝牙
            blueAdapter.enable();
        } else {
            blueAdapter.startDiscovery();
            blueAdapter.startLeScan(startCall);
        }

        //判断蓝牙是否正在扫描，如果是调用取消扫描方法；如果不是，则开始扫描
        if (blueAdapter.isDiscovering()) {
            blueAdapter.cancelDiscovery();
        } else
            blueAdapter.startDiscovery();

        bleAdapter.setOnAdapterItemClickListener(position -> {

            blueAdapter.stopLeScan(stopCall);

            Intent intent = new Intent(BlueToothActivity.this, ControlActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("blue", mData.get(position).getBluetoothDevice());
            intent.putExtras(bundle);
            startActivity(intent);
        });
    }

    BluetoothAdapter.LeScanCallback startCall = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int i, byte[] bytes) {
            //device为扫描到的BLE设备
            //E0:B6:55:BB:0B:E9---客厅的小米电视
            //D0:11:66:39:51:26---MI Band 2
            //54:48:E6:7D:E7:22
            //41:8B:DD:14:D9:00
            //30:21:DC:63:59:E2---A5
            if (device != null && device.getName() != null /*&& device.getName().contains("JDY")*/) {
//                LogUtils.d(device.getAddress() + "---" + device.getName());
                for (int j = 0; j < mData.size(); j++) {
                    if (mData.get(j).getAddress().equals(device.getAddress())) {
                        return;
                    }
                }
                BleModel bleModel = new BleModel();
                bleModel.setDeviceName(device.getName() == null ? device.getAddress() : device.getName());
                bleModel.setAddress(device.getAddress());
                bleModel.setBluetoothDevice(device);
                mData.add(bleModel);
                bleAdapter.notifyDataSetChanged();//更新
            }
        }
    };

    BluetoothAdapter.LeScanCallback stopCall = (device, i, bytes) -> {
        LogUtils.d("停止扫描");
    };

    protected void onDestroy() {
        super.onDestroy();//解除注册
        if (blueAdapter != null) {
            blueAdapter.cancelDiscovery();
            blueAdapter.stopLeScan(stopCall);
        }
        if (bluetoothReceiver != null) {
            unregisterReceiver(bluetoothReceiver);
        }
    }

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            LogUtils.i("蓝牙正在打开中");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            LogUtils.i("蓝牙已经打开");
                            blueAdapter.startDiscovery();
                            blueAdapter.startLeScan(startCall);
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            LogUtils.i("蓝牙正在关闭中");
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            LogUtils.i("蓝牙已经关闭");
                            break;
                    }
                    break;
                case BluetoothDevice.ACTION_FOUND:
                    LogUtils.i("发现蓝牙");
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                    for (int i = 0; i < mData.size(); i++) {
                        if (device.getAddress().equals(mData.get(i).getAddress())) {
                            return;
                        }
                    }
                    BleModel bleModel = new BleModel();
                    bleModel.setDeviceName(device.getName() == null ? device.getAddress() : device.getName());
                    bleModel.setAddress(device.getAddress());
                    bleModel.setBluetoothDevice(device);
                    mData.add(bleModel);
                    bleAdapter.notifyDataSetChanged();//更新
                    break;
            }
        }
    };
}